<!-- author: xuett -->
<!-- date: 2025-05-21 10:47:27 -->
<!-- description: 列表页 -->
<template>
  <div class="list-container">
    <!-- 列表内容 -->
    <div class="list-content">
      <div v-if="$musicStore.musicList.length > 0" class="list-box">
        <div class="list-total">共有 {{ $musicStore.musicList.length }} 个音频文件</div>
        <div class="music-list">
          <div v-for="file in $musicStore.musicList" :key="file.path" class="music-item">
            <div class="file-name">{{ file.name }}</div>
            <div class="file-meta">
              <span class="file-extension">{{ file.extension }}</span>
              <button @click="loadAudio(file)" class="play-button">▶ 播放</button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 播放条 -->
    <div class="play-box">
      <div class="btn-box">
        <el-icon v-if="isPlay" @click="pauseAudio"><VideoPause /></el-icon>
        <el-icon v-else @click="playAudio"><VideoPlay /></el-icon>
      </div>
      <div class="player-controls">
        <div class="left-time">{{ currentTime }}</div>
        <input
          class="progress-bar"
          type="range"
          id="progressBar"
          min="0"
          :max="duration"
          value="0"
        />
        <div class="right-time">{{ formatTime(duration) }}</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { useMusicStore } from '@/store/modules/music'
import { getAudioInfo } from '@/utils/audio'

const $musicStore = useMusicStore()
let audioPlayer = null
const state = reactive({
  currentTime: '00:00',
  duration: '00:00',
  isPlay: false
})
const { currentTime, duration, isPlay } = toRefs(state)

// const play = async (val) => {
//   audioPlayer = await playAudio(val.path)
//   // 获取音频总时长（需等待元数据加载）
//   audioPlayer.addEventListener('loadedmetadata', () => {
//     $musicStore.updateCurrentPlay({
//       id: val.id,
//       name: val.name,
//       path: val.path,
//       duration: val.duration,
//       extension: val.extension,
//       currentTime: '00:00'
//     })
//   })

//   // 监听时间更新事件
//   audioPlayer.addEventListener('timeupdate', () => {
//     console.log('当前播放时间:', audioPlayer.currentTime)
//     $musicStore.updateCurrentPlayTime(audioPlayer.currentTime)
//   })
// }

let audioContext
let sourceNode
let audioBuffer
const loadAudio = async (val) => {
  getAudioInfo(val.path)
  // 通过 Electron 的 IPC 获取音频数据
  const result = await window.api.getFileBufByFilePath(val.path)

  // 创建音频上下文
  audioContext = new (window.AudioContext || window.webkitAudioContext)()

  // 解码音频数据
  audioBuffer = await audioContext.decodeAudioData(result.buffer.buffer)
  state.duration = audioBuffer.duration
  playAudio()
}

function playAudio() {
  if (!audioBuffer) return
  // 停止当前播放（如果正在播放）
  if (sourceNode) {
    sourceNode.stop()
  }
  sourceNode = audioContext.createBufferSource()
  sourceNode.buffer = audioBuffer
  sourceNode.connect(audioContext.destination)
  // 记录开始时间
  state.currentTime = audioContext.currentTime
  console.log('开始播放', state.currentTime)

  // 监听播放进度
  sourceNode.onended = () => {
    console.log('播放结束')
  }

  // 开始播放
  sourceNode.start(0)
  // 更新进度条
  requestAnimationFrame(updateProgress)
}

const pauseAudio = () => {
  if (sourceNode) {
    sourceNode.stop()
  }
  state.isPlay = false
}

function updateProgress() {
  if (sourceNode) {
    state.currentTime = formatTime(audioContext.currentTime)
    console.log('当前播放时间', state.currentTime)

    const percent = (audioContext.currentTime / audioContext.duration) * 100

    document.getElementById('progressBar').value = audioContext.currentTime

    if (state.isPlay && audioContext.currentTime < audioBuffer.duration) {
      requestAnimationFrame(updateProgress)
    } else {
      state.isPlay = false
    }
  }
}

function formatTime(seconds) {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = Math.floor(seconds % 60)
  return `${minutes}:${remainingSeconds < 10 ? '0' : ''}${remainingSeconds}`
}

// 点击进度条跳转
// progressBar.addEventListener('input', () => {
//   const seekTime = (progressBar.value / 100) * audioPlayer.duration
//   audioPlayer.currentTime = seekTime
// })
</script>

<style scoped lang="scss">
.list-container {
  width: 100%;
  height: 100%;
  padding: 20px;
  .list-content {
    width: 100%;
    height: calc(100% - 100px);
    border-bottom: 1px solid #ccc;
    .list-total {
      width: 100%;
      height: 50px;
    }
    .music-list {
      width: 100%;
      height: calc(100% - 50px);
      padding-right: 10px;
      overflow-y: auto;
      .music-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px;
        border-bottom: 1px solid #eee;
        &:last-child {
          border-bottom: none;
        }
        .play-button {
          background-color: #2196f3;
          color: white;
          border: none;
          padding: 5px 10px;
          border-radius: 3px;
          cursor: pointer;
        }

        .play-button:hover {
          background-color: #0b7dda;
        }
      }
    }
  }
  .play-box {
    width: 100%;
    height: 100px;
    .player-controls {
      width: 100%;
      display: flex;
      .left-time,
      .right-time {
        width: 60px;
      }
      .progress-bar {
        width: calc(100% - 150px);
        margin: 0 15px;
      }
    }
  }
}
</style>
